<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\trade;

use Doraemon\tools\ImgUrl as toolImgUrl;
use Medoo\Medoo;

class OrderGoods extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_trade';

    const _DATABASE_ = 'shop_trade';

    const _TABLE_NAME = 'order_goods';


    //虚拟状态
    const REFUND_STATUS_CAN_NOT_REFUND = 0;//虚拟状态，不可退款
    const REFUND_STATUS_CAN_REFUND = 1;//虚拟状态，可退款


    public $vRefundStatusDesc = [
        self::REFUND_STATUS_CAN_REFUND => '可退款',
        self::REFUND_STATUS_CAN_NOT_REFUND => '不可退款'
    ];

    public static function insertOrderGoods($data)
    {
        return self::insert($data)->rowCount();
    }

    public static function getOrderGoodsFromMaster($orderNo)
    {
        $list = self::select_master("*", Medoo::raw(' where order_no=:orderNo for update', [':orderNo' => $orderNo]));

        if (empty($list)) {
            return [];
        }

        foreach ($list as &$info) {
            self::formatInfo($info);
        }

        return $list;
    }


    public static function getOrderGoodsList($orderNo, $skuIds = [], $indexKey = 'sku_id', $field = '*')
    {
        $where = ['order_no' => $orderNo];
        if (!empty($skuIds)) {
            $where['sku_id'] = $skuIds;
        }

        $list = self::select($field, $where);

        if (empty($list)) {
            return [];
        }
        if (is_string($orderNo) && $indexKey) {
            $list = array_column($list, null, $indexKey);
        }

        foreach ($list as &$info) {
            self::formatInfo($info);
        }

        return $list;
    }


    public static function getFieldsByOrderNo($orderNo, $fields = '*')
    {
        $list = self::select($fields, ['order_no' => $orderNo]);
        if (empty($list)) {
            return [];
        }

        foreach ($list as &$info) {
            self::formatInfo($info);
        }

        return $list;
    }

    public static function getSkuInfo($orderNo, $skuId)
    {

        $info = self::select("*", Medoo::raw(' where order_no=:orderNo and sku_id=:skuId', [':orderNo' => $orderNo, ':skuId' => $skuId]));

        $info = array_shift($info);

        if (empty($info)) {
            return false;
        }

        self::formatInfo($info);

        return $info;
    }

    public static function getSkuInfoFromMaster($orderNo, $skuId)
    {

        $info = self::select_master("*", Medoo::raw(' where order_no=:orderNo and sku_id=:skuId for update', [':orderNo' => $orderNo, ':skuId' => $skuId]));

        $info = array_shift($info);

        if (empty($info)) {
            return false;
        }

        self::formatInfo($info);

        return $info;
    }

    public static function formatInfo(&$info)
    {
        if ($info) {
            foreach ($info as $field => &$value) {
                switch ($field) {
                    case 'cover_img':
                        $info['cover_img_url'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $value, toolImgUrl::IMAGE_SIZE_ORI_NPHONE);
                        $info['cover_img_thumb_url'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $value, toolImgUrl::IMAGE_SIZE_SQ_THUMB);
                        break;
                }
            }
        }
    }

    public static function getFirstSkuInfo($orderNo, $whereSkuIds = [])
    {
        $where = ['order_no' => $orderNo, 'ORDER' => ['id' => 'ASC']];

        $where = array_merge($where, $whereSkuIds);

        $info = self::get('*', $where);

        self::formatInfo($info);

        return $info;
    }

    public static function getUserOrderGoodsIds($uid, $orderNos)
    {
        return self::select('goods_id', ['uid' => $uid, 'order_no' => $orderNos]);
    }

    public static function getOrderNosByGoodsId($goodsId)
    {
        $orderNos = self::select(['order_no'], ['goods_id' => $goodsId]);

        if (empty($orderNos)) {
            return false;
        }
        return array_column($orderNos, 'order_no');
    }

    public static function getOrderNosBySkuId($skuId)
    {
        $orderNos = self::select(['order_no'], ['sku_id' => $skuId]);

        if (empty($orderNos)) {
            return false;
        }
        return array_column($orderNos, 'order_no');
    }

    public static function getUserBoughtGoodsIds($uid, $limit = [])
    {
        $where = [
            'AND' => [
                'uid' => $uid,
            ],
            'GROUP' => 'goods_id',
        ];
        $result = self::select(['goods_id', 'addtimes' => Medoo::raw("GROUP_CONCAT(UNIX_TIMESTAMP(<addtime>))")], $where);
        $arr = [];
        if ($result) {
            foreach ($result as $row) {
                $goodsId = $row['goods_id'];
                $addtimes = $row['addtimes'];
                $addtimesArr = $addtimes ? explode(',', $addtimes) : [];
                if ($addtimesArr) {
                    $arr[$goodsId] = max($addtimesArr);
                }
            }
        }
        return $arr;
    }

    public static function getSkuIds($orderNo)
    {
        $list = self::select(['sku_id'], ['order_no' => $orderNo]);

        return array_column($list, 'sku_id');
    }

    public static function getInfosByOrderNo($orderNo, $filed = '*')
    {
        return self::select($filed, ['order_no' => $orderNo]);
    }


    public static function getInfosByActivityType($activityType, $activityId)
    {
        return self::select("*", [
            'promo_type' => $activityType,
            'promo_id' => $activityId
        ]);
    }

    /**
     * @desc 获取支付金额最多的商品排名数据
     * @note
     * @param string $startTime 起始时间
     * @param string $endTime 截止时间
     * @param array $testShopIds 测试店铺id集合
     * @return array
     */
    public static function getPayRankGoodsIds($startTime, $endTime, array $testShopIds = [])
    {
        $fields = 'goods_id';
        $where = [
            "addtime[>]" => $startTime,
            "addtime[<]" => $endTime,
            "GROUP" => "goods_id",
        ];
        if ($testShopIds) {
            $where['shop_id[!]'] = $testShopIds;
        }
        $rs = self::select($fields, $where);
//        var_dump(self::log());
        return $rs;
    }

    /**
     * @desc 获取支付金额最多的商品排名数据
     * @note
     * @param string $startTime 起始时间
     * @param string $endTime 截止时间
     * @param int $limit 记录数量
     * @param array $testShopIds 测试店铺id集合
     * @param array $goodsIds 商品id集合
     * @return array
     */
    public static function getPayAmountRank($startTime, $endTime, $limit = 10, array $testShopIds = [], array $goodsIds = [])
    {
        $fields = [
            'goods_id',
            'sums' => Medoo::raw('SUM(<pay_amount>)')
        ];
        $where = [
            "addtime[>]" => $startTime,
            "addtime[<]" => $endTime,
            "GROUP" => "goods_id",
            "ORDER" => ["sums" => "DESC", "goods_id" => "DESC"],
            "LIMIT" => $limit,
        ];
        if ($testShopIds) {
            $where['shop_id[!]'] = $testShopIds;
        }
        if ($goodsIds) {
            $where['goods_id'] = $goodsIds;
        }
        $rs = self::select($fields, $where);
//        var_dump(self::log());
        return $rs;
    }

    /**
     * @desc 获取下单最多的商品排名数据
     * @note
     * @param string $startTime 起始时间
     * @param string $endTime 截止时间
     * @param int $limit 记录数量
     * @param array $testShopIds 测试店铺id集合
     * @param array $goodsIds 商品id集合
     * @return array
     */
    public static function getBuyAmountRank($startTime, $endTime, $limit = 10, array $testShopIds = [], array $goodsIds = [])
    {
        $fields = [
            'goods_id',
            'count' => Medoo::raw('COUNT(*)')
        ];
        $where = [
            "addtime[>]" => $startTime,
            "addtime[<]" => $endTime,
            "GROUP" => "goods_id",
            "ORDER" => ["count" => "DESC", "goods_id" => "DESC"],
            "LIMIT" => $limit,
        ];
        if ($testShopIds) {
            $where['shop_id[!]'] = $testShopIds;
        }
        if ($goodsIds) {
            $where['goods_id'] = $goodsIds;
        }
        return self::select($fields, $where);
    }


    public static function getUserOrdersByGoodsId($uid, $goodsId, $fields = '*')
    {
        return self::select($fields, ['uid' => $uid, 'goods_id' => $goodsId]);
    }

    /**
     * 根据sku_id获取购买总数
     * @param $skuIds
     * @return array
     */
    public static function admGetCartNumBySkuIds($skuIds)
    {
        $result = self::select(['sku_id', 'count' => Medoo::raw("count('buy_num')")], [
            'AND' => [
                'sku_id' => $skuIds,
            ],
            'GROUP' => ['sku_id']
        ]);

        return $result ?: [];

    }

    public static function updateData($data, $where)
    {
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }
}